package day2;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import utility.JdbcUtils;


public class BatchTest {
	public static void main(String[] args) throws SQLException,InterruptedException {
		long begin=System.currentTimeMillis();
		insertOneByOne();
		long end=System.currentTimeMillis();
		System.out.println("insertOneByOne cost :"+(end-begin));
		
		begin=System.currentTimeMillis();
		insertByBatch();
		end=System.currentTimeMillis();
		System.out.println("insertByBatch cost :"+(end-begin));
		
		
	}

	private static void insertOneByOne () throws SQLException {
		// TODO Auto-generated method stub
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int count=0;
		int j=0;
		try {
			// 2.建立连接
			con = JdbcUtils.getConnection();
			// 3.创建语句
			String sql = "insert into user(name,birthday, money) values (?, ?, ?) ";
			ps = con.prepareStatement(sql);
			for(int i=0;i<10000;i++){
				ps.setString(1, "no batch name" + i);
				ps.setDate(2, new Date(System.currentTimeMillis()));
				ps.setFloat(3, 100f + i);
				j=ps.executeUpdate();
				count+=j;
			}
			System.out.println("insertOneByOne run times = "+ count);

		}finally{
			JdbcUtils.free(rs, ps, con);
			
		}
	}

	private static void insertByBatch() throws SQLException {
		// TODO Auto-generated method stub
		Connection con = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		int count[];
		try {
			// 2.建立连接
			con = JdbcUtils.getConnection();
			// 3.创建语句
			String sql = "insert into user(name,birthday, money) values (?, ?, ?) ";
			ps = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
			for(int i=0;i<10000;i++){
				ps.setString(1, "no batch name" + i);
				ps.setDate(2, new Date(System.currentTimeMillis()));
				ps.setFloat(3, 100f + i);
				ps.addBatch();
			}
			count=ps.executeBatch();
			int sum=0;
			for(int i:count){
				sum+=i;
			}
			System.out.println("insertByBatch run times = "+sum);

		}finally{
			JdbcUtils.free(rs, ps, con);
		}
	}
}
